package com.sentongo.joetrackersample;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Pattern;

import org.achartengine.ChartFactory;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
//import android.webkit.ConsoleMessage;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements SensorEventListener, android.view.View.OnClickListener {
	
	private boolean firstrun = true;
	private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private float upperXThreshold, upperYThreshold, upperZThreshold, lowerXThreshold, lowerYThreshold, lowerZThreshold = 0;
	private boolean ignoreGarbage = true;
	private boolean subtractError = false;
	long t = 0;
   
    // define the display assembly compass picture
    private ImageView image;
    
    // record the compass picture angle turned
    private float currentDegree = 0f;
    
    // device sensor manager
    private SensorManager mSensorManagerCmps;

    TextView tvHeading;

    //Used for graph
    private SensorManager sensorManager;
	private Button btnStart, btnStop, btnUpload, btnCalibrate;
	private boolean started = false;
	private ArrayList<AccData> sensorData;
	private ArrayList<AccData> sensorDataCalib;
	private LinearLayout layout, calibrateContainer;
	private View mChart;
    
	private long startTime = 0L;
	private Handler customHandler = new Handler();
	private Handler customHandlerCalib = new Handler();
	long timeInMilliseconds = 0L;
	long timeSwapBuff = 0L;
	long updatedTime = 0L;
	private TextView timerValue, calibrate_results, calibrate_user_info, calib_timer;
	
	
	private boolean filterNoise = false;  // Set to true once calibration is completed.
	private int samplesCountTest = 0;
	
	private float lastX =0, lastY =0, lastZ =0, lastDistanceY=0, previousMilliseconds = 0, lastDistanceX=0;
	private float velocityLast = 0;
	private int calibrationCountDown = 15;
	private int milliseconds;
	private int lastSecond = 0;
	
	
	
	float x;
	float y;
	float z;
	float gX = 0; // Gravity 
	float gY = 0;
	float gZ = 0;
	
	float xSum = 0, ySum =0, zSum = 0, overAll = 0;
	float avgX = 0, avgY = 0, avgZ = 0, overAllAvg = 0;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mSensorManager.registerListener(this, mAccelerometer , SensorManager.SENSOR_DELAY_FASTEST);
        
        
        image = (ImageView) findViewById(R.id.imageViewCompass);
 
        // TextView that will tell the user what degree is he heading
        tvHeading = (TextView) findViewById(R.id.tvHeading);
        
        calibrate_user_info = (TextView) findViewById(R.id.calibrate_user_info); 
        calib_timer = (TextView) findViewById(R.id.calib_timer);
        calibrate_results = (TextView) findViewById(R.id.calibrate_results);

        // initialize your android device sensor capabilities
        mSensorManagerCmps = (SensorManager) getSystemService(SENSOR_SERVICE);
        timerValue = (TextView) findViewById(R.id.timerValue);
        //calibCountdohwn = (TextView) findViewById(R.id.calib_timer);
        
        
        // Graph settings
        layout = (LinearLayout) findViewById(R.id.chart_container);
        calibrateContainer = (LinearLayout) findViewById(R.id.calibrateContainer);
		sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		sensorData = new ArrayList<AccData>();

		btnStart = (Button) findViewById(R.id.btnStart);
		btnStop = (Button) findViewById(R.id.btnStop);
		btnUpload = (Button) findViewById(R.id.btnUpload);
		btnCalibrate = (Button) findViewById(R.id.calib_btn);
		
		btnStart.setOnClickListener(this);
		btnStop.setOnClickListener(this);
		btnUpload.setOnClickListener(this);
		btnCalibrate.setOnClickListener(this);
		btnCalibrate.setEnabled(true);
		//btnStart.setEnabled(false);
		btnStop.setEnabled(false);
		if (sensorData == null || sensorData.size() == 0) {
			btnUpload.setEnabled(false);
		}
    }

    @SuppressWarnings("deprecation")
	protected void onResume() {
        super.onResume();
        mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);
        
     // for the system's orientation sensor registered listeners
        mSensorManagerCmps.registerListener(this, mSensorManagerCmps.getDefaultSensor(Sensor.TYPE_ORIENTATION),
        		SensorManager.SENSOR_DELAY_FASTEST);

    
    }

    protected void onPause() {
        super.onPause();
        mSensorManager.unregisterListener(this);
     // to stop the listener and save battery
        mSensorManagerCmps.unregisterListener(this);
        if (started == true) {
            sensorManager.unregisterListener(this);
        }
    
    }

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// ignore 
	}

	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public void onSensorChanged(SensorEvent event) {
			
		Sensor sensor = event.sensor;
		if(sensor.getType() == Sensor.TYPE_ACCELEROMETER){
			
			TextView tvX= (TextView)findViewById(R.id.x_axis);
			TextView tvY= (TextView)findViewById(R.id.y_axis);
			TextView tvZ= (TextView)findViewById(R.id.z_axis);
			
			x = event.values[0];
			y = event.values[1];
			z = event.values[2];
			
			

			//Filter to eliminate gravity
			float alpha = 0.8f;
			
			gX = alpha * gX + (1-alpha) * x;
			gY = alpha * gY + (1-alpha) * y;
			gZ = alpha * gZ + (1-alpha) * z;
			
			x = x - gX;
			y = y - gY;
			z = z - gZ;
			
			
			if (started) {								
				// Remove Noise
				if(filterNoise && ignoreGarbage){
					if(x>0f){
						if(x<upperXThreshold){
							x=0;
							tvX.setText(Float.toString(x));
						}
						
						else tvX.setText(Float.toString(x));
					}
					if(x<0f){
						if(x>lowerXThreshold){
							x=0;
							tvX.setText(Float.toString(x));
						}
						else tvX.setText(Float.toString(x));
					}
					if(y>0f){
						if(y<upperYThreshold){
							y=0;
							tvY.setText(Float.toString(y));
						}
						else tvY.setText(Float.toString(y));
					}
					if(y<0f){
						if(y>lowerYThreshold){
							y=0;
							tvY.setText(Float.toString(y));
						}
						else tvY.setText(Float.toString(y));
					}
					if(z>0f){
						if(z<upperZThreshold){
							z=0;
							tvZ.setText(Float.toString(z));
						}
						else tvZ.setText(Float.toString(z));
					}
					if(z<0f){
						if(z>lowerZThreshold){
							z=0;
							tvZ.setText(Float.toString(z));
						}
						else tvZ.setText(Float.toString(z));
					}					
				}
				
				
				else if(subtractError){
					x = x - avgX;
					y = y - avgY;
					z = z - avgZ;
					tvX.setText(Float.toString(x));
					tvZ.setText(Float.toString(z));
					tvY.setText(Float.toString(y));
					
				}
				
	
				
				if(!filterNoise){
					tvX.setText(Float.toString(x));
					tvZ.setText(Float.toString(z));
					tvY.setText(Float.toString(y));			
				}
				}
			
			if(firstrun){
				lastX = 0;
				lastY = 0;
				lastZ = 0;
				
				firstrun = false;
			}
			else{
				lastX = x;
				lastY = y;
				lastZ = z;
			}
			
			
				
		}
		if (sensor.getType() == Sensor.TYPE_ORIENTATION){
			// Compass Code
			
						// get the angle around the z-axis rotated
						float degree = Math.round(event.values[0]);
						
						// Display heading direction.
						String direction = "North";
						if(degree > 49.0 && degree < 145.0  ){
							direction = "East";
						}
						if(degree > 145.0 && degree < 242.0){
							direction = "South";
						}
						if(degree > 242.0 && degree < 325.0){
							direction = "West";					
												}
						if(degree > 325.0 && degree < 49.0 ){
							direction = "North";
						}
						if(degree == 0.0 ){
							direction = "North";
						}
						
						//tvHeading.setText("Facing: " + Float.toString(degree) + " degrees. " + "("+ direction +")");
						// create a rotation animation (reverse turn degree degrees)
						RotateAnimation ra = new RotateAnimation(currentDegree,
								-degree,
								Animation.RELATIVE_TO_SELF, 0.5f,
								Animation.RELATIVE_TO_SELF,
								0.5f);
						// how long the animation will take place
						ra.setDuration(210);
						// set the animation after the end of the reservation status
						ra.setFillAfter(true);
						// Start the animation
						//image.startAnimation(ra);
						currentDegree = -degree;			
		
			
		}
	
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnStart:
			
			resetSensorVariables(); // Reset all sensor variables
			btnStart.setEnabled(false);
			btnStop.setEnabled(true);
			btnUpload.setEnabled(false);
			sensorData = new ArrayList<AccData>();
			started = true;
			Sensor accel = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
			sensorManager.registerListener(this, accel,SensorManager.SENSOR_DELAY_FASTEST);
			//Pause (prevent spikes at start up
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			filterNoise = true;
			/*Sensor compass = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
			mSensorManager.registerListener(this, compass,SensorManager.SENSOR_DELAY_FASTEST);*/
			startTime = SystemClock.uptimeMillis();
			customHandler.postDelayed(updateTimerThread, 0);
			layout.setVisibility(View.GONE);
			calibrateContainer.setVisibility(View.GONE);
			image.setVisibility(View.VISIBLE);

			
			break;
		case R.id.btnStop:
			filterNoise = false;
			btnStart.setEnabled(true);
			btnStop.setEnabled(false);
			btnUpload.setEnabled(true);
			started = false;
			sensorManager.unregisterListener(this);
			layout.removeView(mChart);
			customHandler.removeCallbacks(updateTimerThread);
			image.setVisibility(View.GONE);
			calibrateContainer.setVisibility(View.GONE);
			layout.setVisibility(View.VISIBLE);
			openChart();

			// show data in chart
			break;
		case R.id.btnUpload:
			saveData();
			btnCalibrate.setEnabled(true);
			ignoreGarbage = true;
			subtractError = false;
			
			
			

			break;
			
		case R.id.calib_btn:
			
			resetSensorVariables();
			// Disable all buttons
			btnStart.setEnabled(false);
			btnStop.setEnabled(false);
			btnUpload.setEnabled(false);
			btnCalibrate.setEnabled(false);
			started = true;
			//Pause (prevent spikes at start up
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Sensor accel2 = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
			sensorManager.registerListener(this, accel2,SensorManager.SENSOR_DELAY_FASTEST);
			
			layout.setVisibility(View.GONE);
			image.setVisibility(View.GONE);
			
			calibrateContainer.setVisibility(View.VISIBLE);
			//calibrate_user_info.setVisibility(View.VISIBLE); 
	        //calib_timer.setVisibility(View.VISIBLE);
			//calibrate_results.setVisibility(TextView.VISIBLE);
			sensorDataCalib = new ArrayList<AccData>();
			startTime = SystemClock.uptimeMillis();
			customHandlerCalib.postDelayed(calibrateAccSensor, 0);
			
			//layout.setVisibility(View.GONE);
			//image.setVisibility(View.GONE);
			
			
			
			break;
		default:
			break;
		}

	}

	@SuppressLint("SimpleDateFormat")
	private void saveData() {
		// TODO Auto-generated method stub
		
		try {
			
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			//get current date time with Date()
			Date date = new Date();
			String datel = dateFormat.format(date).toString();
			String datel2 = datel.replaceAll(Pattern.quote("/")," ").replaceAll(Pattern.quote(":")," ");
			String extrName = Environment.getExternalStorageDirectory().toString()+"/accData "+datel2;
            File myFile = new File(extrName+".txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
           
            myOutWriter.append("time,x,y,z\n");
            for (AccData data : sensorData) {
            	myOutWriter.append(data.getTimestamp()-t + "," + data.getX() + "," + data.getY() + "," + data.getZ() + "\n");
			}

            
            
            myOutWriter.close();
            fOut.close();
            Toast.makeText(getBaseContext(),"Done writing to SD '"+extrName+".txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
        	DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        	Date date = new Date();
        	String datel = dateFormat.format(date).toString();
        	String datel2 = datel.replaceAll(Pattern.quote("/")," ").replaceAll(Pattern.quote(":")," ");
        	String extrName = Environment.getExternalStorageDirectory().toString()+"/accData "+datel2;
        	Toast.makeText(getBaseContext(), e.getMessage(),
                    Toast.LENGTH_LONG).show();
            Toast.makeText(getBaseContext(), extrName, Toast.LENGTH_LONG).show();
        }
		
	}

	private void resetSensorVariables() {
		lastDistanceY =0;
		lastX =0;
		lastSecond = 0;
		velocityLast = 0;
		lastDistanceX=0;
		currentDegree = 0f;
		previousMilliseconds = 0;
		gX = 0; // Gravity
		gY = 0;
		gZ = 0;
		startTime = 0L;
	}
	
	
	private void openChart() {
		if (sensorData != null || sensorData.size() > 0) {
			t = sensorData.get(0).getTimestamp();
			XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();

			XYSeries xSeries = new XYSeries("X");
			XYSeries ySeries = new XYSeries("Y");
			XYSeries zSeries = new XYSeries("Z");

			for (AccData data : sensorData) {
				xSeries.add(data.getTimestamp() - t, data.getX());
				ySeries.add(data.getTimestamp() - t, data.getY());
				zSeries.add(data.getTimestamp() - t, data.getZ());
			}

			dataset.addSeries(xSeries);
			dataset.addSeries(ySeries);
			dataset.addSeries(zSeries);
			

			XYSeriesRenderer xRenderer = new XYSeriesRenderer();
			xRenderer.setColor(Color.RED);
			//xRenderer.setPointStyle(PointStyle.CIRCLE);
			xRenderer.setFillPoints(false);
			xRenderer.setLineWidth(0);
			xRenderer.setDisplayChartValues(false);
			//xRenderer.setDomainStep()
			
			

			XYSeriesRenderer yRenderer = new XYSeriesRenderer();
			yRenderer.setColor(Color.GREEN);
			//yRenderer.setPointStyle(PointStyle.CIRCLE);
			yRenderer.setFillPoints(false);
			yRenderer.setLineWidth(1);
			yRenderer.setDisplayChartValues(false);
		

			XYSeriesRenderer zRenderer = new XYSeriesRenderer();
			zRenderer.setColor(Color.BLUE);
			//zRenderer.setPointStyle(PointStyle.CIRCLE);
			zRenderer.setFillPoints(false);
			zRenderer.setLineWidth(0);
			zRenderer.setDisplayChartValues(false);

			XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
			multiRenderer.setXLabels(1);
			multiRenderer.setLabelsColor(Color.RED);
			multiRenderer.setChartTitle("time vs (x,y,z)");
			multiRenderer.setXTitle("Sensor Data");
			multiRenderer.setYTitle("Acceleration Vales");
			multiRenderer.setAxesColor(Color.RED);
			multiRenderer.setApplyBackgroundColor(true);
			multiRenderer.setBackgroundColor(Color.BLACK);
			multiRenderer.setShowGrid(true);			
			multiRenderer.setZoomButtonsVisible(true);
			
			
			
			multiRenderer.setYLabelsAlign(Align.RIGHT);
			
			
			for (int i = 0; i < sensorData.size(); i++) {
				if(i%1000 == 0){
					multiRenderer.addXTextLabel(i + 1, "" + (sensorData.get(i).getTimestamp()-t));
				}
				
			}
			for (int i = 0; i < 12; i++) {
				multiRenderer.addYTextLabel(i + 1, ""+i);
			}

			multiRenderer.addSeriesRenderer(xRenderer);
			multiRenderer.addSeriesRenderer(yRenderer);
			multiRenderer.addSeriesRenderer(zRenderer);


			//Line Chart
			mChart = ChartFactory.getLineChartView(getBaseContext(), dataset,
					multiRenderer);

			// Adding the Line Chart to the LinearLayout
			layout.addView(mChart);
			multiRenderer.setBackgroundColor(Color.BLACK);
			
		}
	}

	private Runnable updateTimerThread = new Runnable() {

		public void run() {
			
			timeInMilliseconds = SystemClock.uptimeMillis() - startTime;	
			updatedTime = timeInMilliseconds;		
			int secs = (int) (updatedTime / 1000);
			int mins = secs / 60;
			secs = secs % 60;
			milliseconds = (int) (updatedTime % 1000) + (lastSecond*1000);
						
			if(filterNoise && ignoreGarbage){
				
				if(x>0f){
					if(x<upperXThreshold){
						x=0;
					}
				}
				if(x<0f){
					if(x>lowerXThreshold){
						x=0;
					}
				}
				if(y>0f){
					if(y<upperYThreshold){
						y=0;
					}
				}
				if(y<0f){
					if(y>lowerYThreshold){
						y=0;
					}
				}
				if(z>0f){
					if(z<upperZThreshold){
						z=0;
					}
				}
				if(z<0f){
					if(z>lowerZThreshold){
						z=0;
					}
				}					
			}
			
			
			if(secs >-3){
				
				timerValue.setText("Seconds: " + String.format("%02d", secs));
							
				
			
				AccData data = new AccData(milliseconds, x, y, z);
				sensorData.add(data);
				float mag = (float) Math.sqrt(x*x + y*y + z*z);
				float timeInterval = Math.abs((milliseconds - previousMilliseconds)/1000);
				float newVelocity = Math.abs((y - lastY) * timeInterval);
	            float newDistanceY =  Math.abs(newVelocity * timeInterval + y * (timeInterval*timeInterval)/2);
	            newDistanceY = Math.abs(newDistanceY + lastDistanceY);
	            lastSecond = secs;
	            previousMilliseconds = milliseconds;
	            velocityLast = newVelocity;
				lastDistanceY = newDistanceY;
				
				
				TextView tvS= (TextView)findViewById(R.id.speed);
				TextView tvD= (TextView)findViewById(R.id.distance);
				float UserDistance = round(newDistanceY, 2);
				float userSpeed = round(mag, 2);
				
				tvD.setText("  Distance: " + Float.toString(UserDistance)+" meters.");
				tvS.setText("  Magnitude: " + Float.toString(userSpeed));
				
			}
			customHandler.postDelayed(this, 0);
			
		}
		

	};

	
	private Runnable calibrateAccSensor = new Runnable() {

		public void run() {
			
			timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
			updatedTime = timeInMilliseconds;
			int secs = (int) (updatedTime / 1000);
			int mins = secs / 60;
			secs = secs % 60;
			milliseconds = (int) (updatedTime % 1000) + (lastSecond*1000);
			TextView tvS= (TextView)findViewById(R.id.speed);
			TextView tvD= (TextView)findViewById(R.id.distance);
			calibrate_results.setVisibility(View.GONE);
			tvS.setText("");
			tvD.setText("");
			
			// Skip the first 2 seconds
			if(secs >=3){
				samplesCountTest++;
				AccData data = new AccData(milliseconds, x, y, z);
				sensorDataCalib.add(data);
			}
			
            
			calib_timer.setText(String.format("%02d", calibrationCountDown-secs));
			
			// on the 9th second, we stop collecting accelerometer data.
			if(secs >= calibrationCountDown){
				
				calib_timer.setText("Working...");
				customHandlerCalib.removeCallbacks(calibrateAccSensor);
				determineSensorErrorValue();
				
			}
			
			if(secs < (calibrationCountDown+1.1)){
				customHandlerCalib.postDelayed(this, 0);	
			}
			
			
			
		}

	};
	
	public float round(float d, int decimalPlace) {
	    BigDecimal bd = new BigDecimal(Float.toString(d));
	    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
	    return bd.floatValue();
	}
	


	private void determineSensorErrorValue() {
		
		//Housekeeping
		
		started = false;
		sensorManager.unregisterListener(this);
		customHandlerCalib.removeCallbacks(calibrateAccSensor);
		calib_timer.setVisibility(View.GONE);
		image.setVisibility(View.GONE);
		//image.seth
		calibrate_results.setVisibility(View.VISIBLE);
		calibrateContainer.setVisibility(View.VISIBLE);
		
		
		
		int numOfSamples = sensorDataCalib.size();
		float allowance = 1f;
		for (AccData data : sensorDataCalib ) {
			xSum = (float) (xSum + data.getX());
			ySum = (float) (ySum + data.getY());
			zSum = (float) (zSum + data.getZ());
			overAll = overAll + xSum + ySum + zSum;
			
			
			//Store the maximum and lowest values from each axis.
			if(data.getX()>0f){
				if(upperXThreshold < data.getX())upperXThreshold = (float) data.getX()*allowance;
			}
			if(data.getX()<0f){
				if(lowerXThreshold > data.getX())lowerXThreshold = (float) data.getX();
			}
			
			if(data.getY()>0f){
				if(upperYThreshold < data.getY())upperYThreshold = (float) data.getY();
			}
			if(data.getY()<0f){
				if(lowerYThreshold > data.getY())lowerYThreshold = (float) data.getY();
			}
			
			if(data.getZ()>0f){
				if(upperZThreshold < data.getZ())upperZThreshold = (float) data.getZ();
			}
			if(data.getZ()<0f){
				if(lowerZThreshold > data.getZ())lowerZThreshold = (float) data.getZ();
			}
			
			upperXThreshold=upperXThreshold*allowance;
			upperXThreshold=upperXThreshold*allowance;
			upperXThreshold=upperXThreshold*allowance;
			lowerYThreshold=lowerYThreshold*allowance;
			upperZThreshold=upperZThreshold*allowance;
			lowerZThreshold=lowerZThreshold*allowance;
					
		}
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		avgX = xSum / numOfSamples;
		avgY = ySum / numOfSamples;
		avgZ = zSum / numOfSamples;
		overAllAvg = overAll / numOfSamples;
		
		String methodUsed = "";
		
		if (ignoreGarbage){
			methodUsed = "\nAny values that fall between min-Y and Max-Y \nwill be classed as garbage data and ignored.";
		}
		else if(subtractError){
			methodUsed = "\nMean Y  will be stubtracted from the \nacc. values (to try and minimise noise)";
		}
		
		calibrate_results.setText(
				//" Live samples : " + samplesCountTest
				//+ " , \n" + 
				" Samples of each axis :...." 
				+ numOfSamples 
				+ " , \n" + 
				" Mean x : ....." + avgX
				+ " , \n" + 
				" Mean Y : ....." + avgY
				+ " , \n" + 
				" Mean Z : ....." + avgZ
				+ " , \n" + 
				" Mean (combined x,y,z)  : " + overAllAvg
				+ " , \n" + 
				"--------------------------------------"
				+ " , \n" + 
				"min-X : " + round(lowerXThreshold, 2) + " ,\n" +
				"max-X : " + round(upperXThreshold, 2) + " ,\n" +
				"min-Y : " + round(lowerYThreshold, 2) + " ,\n" +
				"max-Y : " + round(upperYThreshold, 2) + " ,\n" +
				"min-Z : " + round(lowerZThreshold, 2) + " ,\n" +
				"max-Z : " + round(upperZThreshold, 2) + " \n" + methodUsed);
		
		
		// btnCalibrate.setEnabled(false);
		btnStart.setEnabled(true);
		btnUpload.setEnabled(true);

	}
	
	
	
	
}
